<template>
  <div class="wechat-success">
    <div class="success-container">
      <div class="success-card">
        <div class="success-icon">
          <svg width="80" height="80" viewBox="0 0 24 24" fill="#07C160">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
        </div>
        
        <h1 class="success-title">登录成功</h1>
        <p class="success-message">{{ message }}</p>
        
        <div v-if="userInfo" class="user-info">
          <p><strong>用户：</strong>{{ userInfo.name }}</p>
          <p><strong>ID：</strong>{{ userInfo.userId }}</p>
        </div>
        
        <div class="loading-section">
          <div class="loading-spinner"></div>
          <p class="loading-text">正在跳转到主页...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import api from '@/utils/api'
import { initVConsole } from '@/utils/vconsole'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const message = ref('企业微信登录成功！')
const userInfo = ref(null)

onMounted(async () => {
  // 根据用户权限初始化vConsole调试工具
  initVConsole()
  
  try {
    // 获取URL参数
    const token = route.query.token
    const userId = route.query.userId
    const name = route.query.name
    
    if (token) {
      // 设置用户信息显示
      if (userId && name) {
        userInfo.value = {
          userId: userId,
          name: decodeURIComponent(name)
        }
      }
      
      // 同步用户信息
      const correctedUserInfo = await syncWeChatWorkUserInfo(userInfo.value.userId)
      
      if (correctedUserInfo) {
        // 使用修正后的用户信息
        const updatedUserInfo = {
          ...userInfo.value,
          username: correctedUserInfo.username,
          fullName: correctedUserInfo.fullName,
          userPhone: correctedUserInfo.userPhone,
          id: correctedUserInfo.userId
        }
        
        // 保存token和修正后的用户信息到store
        console.log('保存token和修正后的用户信息到store',updatedUserInfo)
        await authStore.setWeChatWorkToken(token, updatedUserInfo)
      } else {
        // 如果获取用户信息失败，使用原始信息但给出警告
        console.warn('获取用户详细信息失败，使用原始企业微信信息')
        await authStore.setWeChatWorkToken(token, userInfo.value)
      }
      
      // 延迟跳转，让用户看到成功信息
      setTimeout(() => {
        router.push('/')
      }, 2000)
    } else {
      // 没有token，跳转到登录页
      setTimeout(() => {
        router.push('/wechat-work-login')
      }, 1000)
    }
  } catch (error) {
    console.error('处理登录成功页面失败:', error)
    setTimeout(() => {
      router.push('/wechat-work-login')
    }, 1000)
  }
})

// 同步企业微信用户信息
const syncWeChatWorkUserInfo = async (wxUserId) => {
  try {
    // 第一步：通过企业微信用户ID获取用户名
    const usernameResponse = await api.post('/api/wechatwork/get-username-by-wxuserid', {
      wxUserId: wxUserId
    })
    
    if (!usernameResponse.data.success) {
      console.error('获取用户名失败:', usernameResponse.data.message)
      return null
    }
    
    const username = usernameResponse.data.data.username
    
    // 第二步：通过用户名获取用户详细信息
    console.log('获取总信息',usernameResponse)
    console.log('获取用户详细信息请求参数:', username)
    const userDetailResponse = await api.post('/api/wechatwork/get-user-detail-by-username', {
      username: username
    })
    console.log('获取用户详细信息响应:', userDetailResponse)
    
    if (!userDetailResponse.data.success) {
      console.error('获取用户详细信息失败:', userDetailResponse.data.message)
      return null
    }
    
    const userDetail = userDetailResponse.data.data
    console.log('获取用户详细信息响应数据:', userDetail)
    return {
      username: userDetail.username,
      fullName: userDetail.fullName,
      userPhone: userDetail.userPhone,
      userId: userDetail.id
    }
  } catch (error) {
    console.error('同步企业微信用户信息失败:', error)
    return null
  }
}
</script>

<style scoped>
.wechat-success {
  min-height: 100vh;
  background: linear-gradient(135deg, #07C160 0%, #00A854 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.success-container {
  width: 100%;
  max-width: 400px;
}

.success-card {
  background: white;
  border-radius: 16px;
  padding: 40px 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.success-icon {
  margin-bottom: 20px;
}

.success-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

.success-message {
  font-size: 16px;
  color: #666;
  margin: 0 0 20px 0;
}

.user-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  text-align: left;
}

.user-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #333;
}

.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #07C160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .wechat-success {
    padding: 10px;
  }
  
  .success-card {
    padding: 30px 20px;
  }
  
  .success-title {
    font-size: 20px;
  }
}
</style>